import fs from 'file-saver'
import XLSX from 'xlsx'
export default (json, fields, filename = '測試數據.xlsx') => {

  json.forEach(item => {
    for (let i in item) {
      if (fields.hasOwnProperty(i)) {
        item[fields[i]] = item[i];
      }
      delete item[i]; //刪除原先的對象屬性
    }
  })

  let sheetName = filename //excel的文件名稱
  let wb = XLSX.utils.book_new()  //工作簿對象包含一SheetNames數組，以及一個表對象映射表名稱到表對象。XLSX.utils.book_new實用函數創建一個新的工作簿對象。
  let ws = XLSX.utils.json_to_sheet(json, { header: Object.values(fields) }) //將JS對象數組轉換為工作表。
  wb.SheetNames.push(sheetName)
  wb.Sheets[sheetName] = ws
  const defaultCellStyle = { font: { name: "Verdana", sz: 13, color: "FF00FF88" }, fill: { fgColor: { rgb: "FFFFAA00" } } };//設置表格的樣式
  let wopts = { bookType: 'xlsx', bookSST: false, type: 'binary', cellStyles: true, defaultCellStyle: defaultCellStyle, showGridLines: false }  //寫入的樣式
  let wbout = XLSX.write(wb, wopts)
  let blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
  fs.saveAs(blob, filename + '.xlsx')
}

const s2ab = s => {
  if (typeof ArrayBuffer !== 'undefined') {
    var buf = new ArrayBuffer(s.length)
    var view = new Uint8Array(buf)
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
    return buf
  } else {
    var buf = new Array(s.length);
    for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
}
